import React, { Component, createRef } from 'react'
import './style.scss'
import NavTab from '@/components/navTab'
import Swiper from '@/components/swiper'
import SearchBtn from '@/components/searchBtn'
import { getSwipersDataApi, hotCategoryApi, goodFoodApi } from '@/service/cookbookApi'
import HotCate from './ui/hotCate'
import GoodFood from '@/components/goodFood'
import { Toast } from 'antd-mobile'

class Index extends Component {
  state = {
    // 页码
    page: 1,
    // 是否还有更多数据了
    hasMore: true,
    // 轮播图数据
    swiperData: [],
    // 热门分类数据
    hotCateData: [],
    // 精品好菜数据
    goodFoodData: []
  }

  moreRef = createRef()

  // 加载轮播图数据
  loadSwiperData = async () => {
    try {
      const ret = await getSwipersDataApi()
      if (ret.code === 0) {
        this.setState({
          swiperData: ret.data
        })
      }
    } catch (error) {
      throw new Error('轮播图数据加载失败')
    }
  }
  // 加载热门分类数据
  loadHotCateData = async () => {
    try {
      const ret = await hotCategoryApi()
      if (ret.code === 0) {
        this.setState({
          hotCateData: ret.data
        })
      }
    } catch (error) {
      throw new Error('热门分类数据加载失败')
    }
  }
  // 加载精品好菜数据
  loadGoodFoodData = async () => {
    try {
      let page = this.state.page
      const ret = await goodFoodApi(page)
      if (ret.code === 0 && ret.data.length > 0) {
        // if (page <= 3) {
        this.setState(state => {
          let goodFoodData = [...state.goodFoodData, ...ret.data]
          if (goodFoodData.length >= 100) {
            goodFoodData = goodFoodData.reverse().slice(0, 100).reverse()
          }
          return {
            goodFoodData,
            page: state.page + 1
          }
        })
      } else {
        this.setState(
          {
            hasMore: false
          },
          () => {
            this.observer.disconnect()
            this.observer = null
          }
        )
      }
    } catch (error) {
      throw new Error('精品好菜数据加载失败')
    }
  }

  componentDidMount() {
    Promise.all([this.loadSwiperData(), this.loadHotCateData()])
      .then(() => {})
      .catch(err => {
        Toast.fail(err.message, 3, () => {}, true)
      })

    // 它也是并发执行，但是它会等待所有的promise对象都执行完毕，不管成功还是失败
    // Promise.allSettled([
    //   this.loadSwiperData(),
    //   this.loadHotCateData(),
    //   this.loadGoodFoodData()
    // ]).then(ret => {
    //   ret.forEach(item => {
    //     if (item.status === 'rejected') {
    //       console.log('数据加载失败', item.reason)
    //     }
    //   })
    // })

    // 观察一个指定的元素是否在可视区域
    this.observer = new IntersectionObserver(entries => {
      // entries是一个数组，里面存放着所有被观察的元素
      // console.log(entries)
      entries.forEach(item => {
        if (item.isIntersecting) {
          // console.log('进入可视区域了')
          this.loadGoodFoodData()
        }
      })
    })
    // 开始观察
    this.moreRef.current && this.observer.observe(this.moreRef.current)
  }

  componentWillUnmount() {
    this.observer.disconnect()
  }

  render() {
    const { swiperData, hotCateData, goodFoodData, hasMore } = this.state
    return (
      <div className='cookbook'>
        <NavTab title='菜谱大全' />
        <Swiper
          items={swiperData}
          onClick={id => {
            this.props.history.push(`/detail/${id}`)
          }}
        />
        <SearchBtn
          title='搜索你想要做的菜？'
          onClick={() => {
            this.props.history.push('/search')
          }}
        />
        <HotCate
          data={hotCateData}
          onClick={row => {
            this.props.history.push(`/cate/${row.id}`)
          }}
        />
        <GoodFood
          data={goodFoodData}
          onClick={item => {
            this.props.history.push(`/detail/${item.id}`)
          }}
        />
        {hasMore ? (
          <div className='more' ref={this.moreRef}>
            正在加载...
          </div>
        ) : (
          <div className='more'>没有更多数据了</div>
        )}
      </div>
    )
  }
}

export default Index
